package com.chinasofti.util;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCtils {
    //私有够发哦方法
    private JDBCtils(){};
    //声明配置信息
    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;
    private static Connection con;

    static{
        try {
            InputStream is = JDBCtils.class.getClassLoader().getResourceAsStream("config.properties");
            Properties prop = new Properties();
            prop.load(is);
            driverClass = prop.getProperty("driverClass");
            url = prop.getProperty("url");
            password = prop.getProperty("password");
            username = prop.getProperty("username");
            //注册驱动
            Class.forName(driverClass);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //设计一个方法，返回数据库连接
    public static Connection getConnection(){
        try {
            con = DriverManager.getConnection(url,username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }

    //释放资源
    public static void close(Connection con, Statement stat, ResultSet rs){
        if(con != null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stat != null){
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void close(Connection con, Statement stat){
        close(con,stat,null);
    }


    public static void main(String[] args) {
        Connection connection = getConnection();
        //System.out.println("connection = " + connection);
        close(connection,null,null);
    }
}